package core.listeners;

import gui.components.CalcTextField;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;

import common.LiteCalculationException;

import core.CalculateCore;
import core.OperationConst;

public class OperationListener implements ActionListener {

	CalcTextField textField = null;
	Double arg1 = null;
	Double arg2 = null;
	Double result = null;
	boolean precalculated = false;
	Integer operation = null;
	String expression = null;
	
	public OperationListener(CalcTextField textField) {
		this.textField = textField;
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		if (e.getSource() instanceof JButton)
		{
			try
			{
				JButton button = (JButton) e.getSource();
				if ("CE".equalsIgnoreCase(button.getText()))
				{
					textField.setText("0");
					arg1 = null;
					arg2 = null;
					result = null;
					operation = null;
				}
				char symbol = button.getText().charAt(0);
				switch (symbol) {
					case '+':
						if (arg1 != null)
						{
							arg2 = new Double(textField.getText());
						}
						else
						{
							arg1 = new Double(textField.getText());
						}
						System.out.println(arg1);
						System.out.println(arg2);
						
						precalculate();
						textField.typed();
						operation = OperationConst.ADDITION;
						break;
					case '=':
						if (arg1 != null && operation != null)
						{
							arg2 = (arg2 == null) ? new Double(textField.getText()) : arg2;
							result = CalculateCore.calculate(arg1, arg2, operation);
							textField.setText(result.toString());
							textField.typed();
							textField.setPrecalculated(true);
							arg1 = result;
						}
						break;
					default:
						break;
				}
			}
			catch (LiteCalculationException e1)
			{
				e1.printStackTrace();
			}
		}
	}
	
	private void precalculate() throws LiteCalculationException
	{
		if (arg1 != null && arg2 != null && !textField.isPrecalculated())
		{
			System.out.println("OperationListener.precalculate()");
			arg1 = CalculateCore.calculate(arg1, arg2, operation);
			textField.setText(arg1.toString());
			textField.setPrecalculated(true);
			arg2 = null;
		}
	}

}
